package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findUserByUserName(String username) {
        User user = userDao.findUserByUserName(username);
        if (null == user) {
            return null;
        }

        Set<Role> roles = roleDao.findRolesByUserId(user.getId());
        if (CollectionUtil.isNotEmpty(roles)) {
            for (Role role : roles) {
                Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                role.setPermissions(permissions);
            }
            user.setRoles(roles);
        }

        return user;
    }

    @Override
    public User findUserByUserNameBatch(String username) {
        User user = userDao.findUserByUserName(username);

        Set<Role> roles = roleDao.findRolesByUserId(user.getId());

        List<Integer> roleIds = getRolesIds(roles);
        //根据角色进行批量查询
        Set<Permission> permissions=permissionDao.findByRoleIdBatch(roleIds);

        Map<Integer,List<Permission>> permissionMap=permissions.stream().collect(Collectors.groupingBy(Permission::getRoleId));

        for (Role role : roles) {
            List<Permission> permissionList = permissionMap.get(role.getId());
            Set<Permission> temp=new HashSet<>();
            temp.addAll(permissionList);
            role.setPermissions(temp);
        }
        return user;
    }

    private List<Integer> getRolesIds(Set<Role> roles) {
        List<Integer> roleIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(roles)) {
            for (Role role : roles) {
                roleIds.add(role.getId());
            }
        }
        return roleIds;
    }


}
